(function($) {
    
    var tabStack = new Array();
	
	$(document).bind("contextmenu", function(e) {   
    	return false;   
    });

	$.getTopWindow = function() {
		var p = window;
		while (p != p.parent) {
			p = p.parent;
		}
		return p;
	};
	
	$.ajaxSetup({
	    complete: function(XMLHttpRequest, textStatus) {
	        var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
	        if (sessionstatus == 'timeout') {
	            $.messager.alert("错误", '登录超时, 请重新登录！', 'error', function() {
	                $.getTopWindow().location.href = "login.action";
	            });
	        }
	    }
	});
	
	$.codeNameCombo = function($option) {
		var codeNameAPI = new CodeNameAPI({
			urlPrefix : $option.urlPrefix
		});

		var paramData = {};
		paramData.type_id = $option.typeId;
		codeNameAPI.search({
			onSuccess : function(codeNameList) {
				if ($option.blank) {
					var blank = {};
					blank.code = "";
					if ($option.blankText) {
						blank.name = $option.blankText;
					} else {
						blank.name = "";
					}
					codeNameList.unshift(blank);
				}
				
				$option.target.combobox({
					required: $option.required,
	 				editable: $option.editable,
	 				multiple: $option.multiple,
	 				readonly: $option.readonly,
	 	            panelHeight: 'auto',
	 				valueField: 'code',
	 				textField: 'name',
	 				value: $option.value,
	 				data: codeNameList,
	 				missingMessage: $option.missingMessage,
	 				onChange: function(newValue, oldValue) {
						if ($option.onChange && typeof($option.onChange) == "function") {
							$option.onChange(newValue, oldValue);
						}
					}
	 			});
			},
			onAPIError : function(status, errors) {
				$.messager.alert($option.errorTitle, $option.errorMessage);
			},
			onServerError : function(jqXHR, textStatus, errorThrown) {
				$.messager.alert($option.errorTitle, $option.errorMessage);
			}
		},
		{
			param: JSON.stringify(paramData)
		});
	};
	
	$.format = function() {
		var s = arguments[0];
		for (var i = 0; i < arguments.length - 1; i++) {
			var reg = new RegExp("\\{" + i + "\\}", "gm");
			s = s.replace(reg, arguments[i + 1]);
		}
		return s;
	};
	
	$.bytes = function() {
		var str = arguments[0];
		return str.replace(/[^\x00-\xff]/g, "**").length;
	};
	
	$(document).keydown(function(event) {
		//Alt + ←/ →
		if ((event.altKey) && ((event.keyCode == 37) || (event.keyCode == 39))) {
			event.returnValue = false;
			return false;
		}
		//Backspace
		if (event.keyCode == 8 && event.target.tagName.toLowerCase() != "input" && event.target.tagName.toLowerCase() != "textarea") {
			return false;
		}
		//F5
		if (event.keyCode == 116) {
			return false;
		}
		//Alt + R
		if ((event.ctrlKey) && (event.keyCode == 82)) {
			return false;
		}
	});
	
	$.loadImage = function(attachmentId, urlPrefix, callback) {
		var attachmentAPI = new AttachmentAPI({
			urlPrefix : urlPrefix
		});
		
		var paramData = {};
		paramData.attachment_id = attachmentId;
		attachmentAPI.loadImage({
			onSuccess : function(imageData) {
				if (imageData.image) {
					callback.onSuccess(imageData.image);
				} else {
					callback.onNoImage();
				}
			},
			onAPIError : function(status, errors) {
				callback.onError(errors);
			},
			onServerError : function(jqXHR, textStatus, errorThrown) {
				callback.onError(errorThrown);
			}
		},
		{
			param: JSON.stringify(paramData)
		});
	}
	
	// 对Date的扩展，将 Date 转化为指定格式的String
	// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
	// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
	// 例子： 
	// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
	// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
	Date.prototype.format = function (fmt) {
	    var o = {
	        "M+": this.getMonth() + 1, //月份 
	        "d+": this.getDate(), //日 
	        "h+": this.getHours(), //小时 
	        "m+": this.getMinutes(), //分 
	        "s+": this.getSeconds(), //秒 
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
	        "S": this.getMilliseconds() //毫秒 
	    };
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	}
	
	$.fn.datebox.defaults.formatter = function(date){
	    return date.format('yyyy-MM-dd');
	}
	
	$.showTenderDetailWindow = function(tenderId) {
	    if (tenderId == undefined || tenderId == "") {
	        return;
	    }
	    $('body').append('<div id="win_tender_detail" style="padding: 5px; margin: 0 auto;"></div>');
	    $('#win_tender_detail').window({
	        href: 'tender_detail.action?tenderId=' + tenderId,
	        title: '招标信息',
	        width: 800,
	        top: 100,
	        modal:true,
	        closed:true,
	        collapsible:false,
	        minimizable:false,
	        maximizable:false,
	        resizable:false,
	        iconCls:'icon-detail',
	        shadow: false
	    }).window('open');
	}
    
    $.showMemberDetailWindow = function(memberLoginName) {
        if (memberLoginName == undefined || memberLoginName == "") {
            return;
        }
        $('body').append('<div id="win_member_detail" style="padding: 5px; margin: 0 auto;"></div>');
        $('#win_member_detail').window({
            href: 'member_detail.action?memberLoginName=' + memberLoginName,
            title: '会员信息',
            width: 700,
            top: 200,
            modal:true,
            closed:true,
            collapsible:false,
            minimizable:false,
            maximizable:false,
            resizable:false,
            iconCls:'icon-man',
            shadow: false
        }).window('open');
    }
    
    $.showQuoteDetailWindow = function(tenderId, memberLoginName) {
        if (tenderId == undefined || tenderId == "") {
            return;
        }
        if (memberLoginName == undefined || memberLoginName == "") {
            return;
        }
        $('body').append('<div id="win_quote_detail" style="padding: 5px; margin: 0 auto;"></div>');
        $('#win_quote_detail').window({
            href: 'quote_detail.action?tenderId=' + tenderId + '&memberLoginName=' + memberLoginName,
            title: '报价信息',
            width: 760,
            top: 200,
            modal:true,
            closed:true,
            collapsible:false,
            minimizable:false,
            maximizable:false,
            resizable:false,
            iconCls:'icon-money',
            shadow: false
        }).window('open');
    }
    
    $.getTabStack = function(index) {
        if (index && typeof(index) == 'Number' && index >= 0) {
            return tabStack[index];
        } else {
            return tabStack;
        }
    }
    
    function TimeCom(dateValue) {
        var newCom = new Date(dateValue);
        this.year = newCom.getYear();
        this.month = newCom.getMonth() + 1;
        this.day = newCom.getDate();
        this.hour = newCom.getHours();
        this.minute = newCom.getMinutes();
        this.second = newCom.getSeconds();
        this.msecond = newCom.getMilliseconds();
        this.week = newCom.getDay();
    }

    function DateDiff(interval, date1, date2) {
        var TimeCom1 = new TimeCom(date1);
        var TimeCom2 = new TimeCom(date2);
        var result;
        switch(String(interval).toLowerCase()) {
            case "y":
            case "year":
                result = TimeCom1.year-TimeCom2.year;
                break;
            case "n":
            case "month":
                result = (TimeCom1.year-TimeCom2.year)*12+(TimeCom1.month-TimeCom2.month);
                break;
            case "d":
            case "day":
                result = Math.round((Date.UTC(TimeCom1.year,TimeCom1.month-1,TimeCom1.day)-Date.UTC(TimeCom2.year,TimeCom2.month-1,TimeCom2.day))/(1000*60*60*24));
                break;
            case "h":
            case "hour":
                result = Math.round((Date.UTC(TimeCom1.year,TimeCom1.month-1,TimeCom1.day,TimeCom1.hour)-Date.UTC(TimeCom2.year,TimeCom2.month-1,TimeCom2.day,TimeCom2.hour))/(1000*60*60));
                break;
            case "m":
            case "minute":
                result = Math.round((Date.UTC(TimeCom1.year,TimeCom1.month-1,TimeCom1.day,TimeCom1.hour,TimeCom1.minute)-Date.UTC(TimeCom2.year,TimeCom2.month-1,TimeCom2.day,TimeCom2.hour,TimeCom2.minute))/(1000*60));
                break;
            case "s":
            case "second":
                result = Math.round((Date.UTC(TimeCom1.year,TimeCom1.month-1,TimeCom1.day,TimeCom1.hour,TimeCom1.minute,TimeCom1.second)-Date.UTC(TimeCom2.year,TimeCom2.month-1,TimeCom2.day,TimeCom2.hour,TimeCom2.minute,TimeCom2.second))/1000);
                break;
            case "ms":
            case "msecond":
                result = Date.UTC(TimeCom1.year,TimeCom1.month-1,TimeCom1.day,TimeCom1.hour,TimeCom1.minute,TimeCom1.second,TimeCom1.msecond)-Date.UTC(TimeCom2.year,TimeCom2.month-1,TimeCom2.day,TimeCom2.hour,TimeCom2.minute,TimeCom2.second,TimeCom1.msecond);
                break;
            case "w":
            case "week":
                result = Math.round((Date.UTC(TimeCom1.year,TimeCom1.month-1,TimeCom1.day)-Date.UTC(TimeCom2.year,TimeCom2.month-1,TimeCom2.day))/(1000*60*60*24)) % 7;
                break;
            default:
                result = "invalid";
        }
        return result;
    }

    function DateAdd(interval, num, dateValue) {
        var newCom = new TimeCom(dateValue);
        switch(String(interval).toLowerCase()) {
            case "y":
            case "year":
                newCom.year += num;
                break;
            case "n":
            case "month":
                newCom.month += num;
                break;
            case "d":
            case "day":
                newCom.day += num;
                break;
            case "h":
            case "hour":
                newCom.hour += num;
                break;
            case "m":
            case "minute":
                newCom.minute += num;
                break;
            case "s":
            case "second":
                newCom.second += num;
                break;
            case "ms":
            case "msecond":
                newCom.msecond += num;
                break;
            case "w":
            case "week":
                newCom.day += num*7;
                break;
            default:
                return "invalid";
        }
        var now = newCom.year + "/" + newCom.month + "/" + newCom.day + " " + newCom.hour + ":" + newCom.minute + ":" + newCom.second;
        return new Date(now);
    }
	
})(jQuery);